<?php
namespace app\scodetrace\controller;

class Scodes extends \app\common\controller\Base {
	protected $modelname='Scode';


	protected function _index(){
		$condition=[];
		$param=$this->param;

    if (isset($param['tcode'])){
      $tmp = model($this->modelname)->byTcode($param['tcode']);
      if ($tmp) {
        $condition[]=['id','=',$tmp->getAttr('id')];
      } else {
        $condition[] =['id','=',0];
      }
    }

    if (isset($param['hcode']))
      $condition[]=['hcode','like',"%".$param['hcode']."%"];

    if (isset($param['acode']))
      $condition[]=['acode','like',"%".$param['acode']."%"];

    if (isset($param['bcode']))
      $condition[]=['bcode','like',"%".$param['bcode']."%"];

    if (isset($param['carriage_code']))
      $condition[]=['carriage_id','in',model('baseinfo/CarriageCode')->where('code',"%".$param['carriage_code']."%")->column('id')];

    if (isset($param['batch_id'])) {
      $condition[]=['batch_id','=',$param['batch_id']];
    } else {
      $batchcondition = [];
      if ($a = isset($param['batch_no']))
        $batchcondition[] = ['serial_number',"=",$param['batch_no']];
      if ($b = isset($param['batch_name']))
        $batchcondition[] = ['name',"like",'%'.$param['batch_name'].'%'];
      if ($a || $b)
        $condition[]=['batch_id',"in",model('batch')->where($batchcondition)->column('id')];
    }

    if (isset($param['first_time']))
      $condition[]=['first_time','between',$param['first_time']];

    if (isset($param['query_amount']))
      $condition[]=['query_amount','between',$param['query_amount']];

		return $condition;
	}

  public function logOne() {
    $ids = $this->param('ids');
    if (!$ids || !is_array($ids)) {
      return json_pack('必须传入要写入log的防伪码的id',400);
    }
    if (!($logtext=$this->param('logtext',null))){
      return json_pack('log内容不能为空',400);
    }
    if (!($area=$this->param('area',null))){
      return json_pack('操作地点不能为空',400);
    }
    if (!($result=$this->param('result',null))){
      return json_pack('操作结果不能为空',400);
    }
    $scodeModel=model('Scode');
    $err=$scodeModel->logOneTrace($ids,$logtext,$area,$result);
    if (!count($err))
      return json_pack('OK');
    else {
      return json_pack($err,400);
    }
  }



  public function create_export_proc() {
    $res_id=$this->param('res_id');
    $cache=cache('SCODE_GEN'.$res_id);
    if (!$cache) {
      return $this->error("你请求的资源不存在，请稍后再试",null,404);
    }
    return json_pack(['processed' => $cache['proc']]);
  }

  public function create_export(){
    $company_id = $this->param('company_id');
    $count = $this->param('count',1);
    if ($count<=0) {
      return json_pack('count必须大于0',400);
    }

    $batch_id = $this->param('batch_id');
    $scodeModel = model('Scode');
    set_time_limit(300);
    ignore_user_abort(true);
    $filename = \think\facade\Env::get('runtime_path')."/scodes";
    if (!file_exists($filename))
      mkdir($filename);
    $filename = tempnam(\think\facade\Env::get('runtime_path')."/scodes",'sc');

    $file = fopen($filename,'wt');
    $filename_zip=$filename.'.zip';
    if (!$file) {
      return json_pack('创建文件缓存失败',400);
    }
    $timestamp = time();
    cache('SCODE_GEN'.$timestamp,['file'=>$filename_zip.'.zip', 'proc'=>0],900);
    $this->json_pack_immediate(['res_id'=>$timestamp]);

    for ($i=$count;$i>0;$i-=10000) {
      $scodes = $scodeModel->batchCreate($i>10000?10000:$i,$company_id,$batch_id);
      if (!$scodes)
        return json_pack($scodeModel->getError(),400);
      foreach ($scodes as $v)
         fprintf($file,"%s,%s,%s\n",$v['tcode'],$v['scode'],'http://'.config('app.app_host')."/query/scode.html?scode=".$v['scode']);
       cache('SCODE_GEN'.$timestamp,['file'=>$filename_zip, 'proc'=>($count-$i)/$count*100],900);
    }
    cache('SCODE_GEN'.$timestamp,['file'=>$filename_zip, 'proc'=>99],900);

    fclose($file);
    $zip = new \ZipArchive();
    $zip->open($filename_zip,\ZipArchive::CREATE);
    $zip->addFile($filename,'result.txt');
    $zip->close();

    cache('SCODE_GEN'.$timestamp,['file'=>$filename_zip, 'proc'=>100],900);
    return;
  }

  public function json_pack_immediate($data,$errcode=200) {
    echo str_repeat(" ",4096);
    echo json_pack($data,$errcode)->getContent();
    header("Content-Length: ".ob_get_length());
    ob_end_flush();
    flush();
    if (function_exists("fastcgi_finish_request")) {
        fastcgi_finish_request();
    }
  }
}

?>